package controller.login;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.impl.UserServiceImpl;
import util.BaseResult;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/registered")
public class RegisteredServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(RegisteredServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");

            BufferedReader reader = req.getReader();
            Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {});

            String username = (String) body.get("username");
            String password = (String) body.get("password");
            String confirm = (String) body.get("confirm");

            if (username == null || username.trim().isEmpty()) {
                sendError(resp, "用户名不能为空", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (password == null || password.length() < 6) {
                sendError(resp, "密码不能少于6位", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (!password.equals(confirm)) {
                sendError(resp, "两次输入密码不一致", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            UserServiceImpl service = new UserServiceImpl();
            boolean sign = service.registered(username, password);

            BaseResult<String> result;
            if (sign) {
                result = BaseResult.success("注册成功");
                resp.setStatus(HttpServletResponse.SC_OK);
            } else {
                result = BaseResult.success("该用户名已存在");
                resp.setStatus(HttpServletResponse.SC_OK);
            }

            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);

        } catch (Exception e) {
            logger.error("注册失败", e);
            sendError(resp, "服务器内部错误: " + e.getMessage(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void sendError(HttpServletResponse resp, String message, int statusCode) throws IOException {
        resp.setStatus(statusCode);
        BaseResult<Void> errorResult = BaseResult.failed(statusCode, message);
        String jsonError = objectMapper.writeValueAsString(errorResult);
        resp.getWriter().write(jsonError);
    }
}